import React from "react";
import { Route, Redirect } from "react-router-dom";
import LoadingFallback from "@src/components/LoadingFallback";
import ErrorBoundary from "@src/components/ErrorBoundary";
import { RouteConfigDeclaration } from "./routes-config";

/**
 * 渲染普通路由
 * @param routesConfig
 * @param extraProps
 */
export const renderRoutes = (routesConfig: RouteConfigDeclaration[], extraProps: any = {}): JSX.Element[] => {
  return routesConfig.map((item, index) => {
    const {
      path,
      exact,
      isProtected,
      isDynamic = true,
      component: Component,
      routes = [],
      loadingFallback,
      name,
      title,
    } = item;
    return (
      <Route
        key={path}
        path={path}
        exact={exact}
        render={(props) => {
          if (isProtected && !localStorage.getItem("token")) {
            return <Redirect key="login-redirect" to="/login" />;
          }
          if (title) document.title = title;
          if (isDynamic) {
            return (
              <ErrorBoundary>
                <React.Suspense fallback={loadingFallback || <LoadingFallback />}>
                  <Component {...props} {...extraProps} routes={routes} />
                </React.Suspense>
              </ErrorBoundary>
            );
          }
          return <Component {...props} {...extraProps} routes={routes} />;
        }}
      />
    );
  });
};

/**
 * 渲染重定向路由
 * @param routes
 */
export function renderRedirectRoute(routes: RouteConfigDeclaration[]): JSX.Element {
  const { path } = routes.find((route) => route.isRedirect) || routes[0];
  return <Redirect key={`${path}-redirect`} to={path} />;
}

/**
 * 渲染所有的路由（普通路由+重定向路由）
 * @param routesConfig
 * @param extraProps
 */
export function renderAllRoutes(routesConfig: RouteConfigDeclaration[], extraProps: any = {}): JSX.Element[] {
  const routes = renderRoutes(routesConfig, extraProps);
  const redirect = renderRedirectRoute(routesConfig);
  return [...routes, redirect];
}
